$(function () {
    $("#jqGrid").jqGrid({
        url: '../book/queryAll',
        datatype: "json",
        colModel: [
            {label: 'id', name: 'id', index: 'id', key: true, align:"center", hidden: true},
                {label: '商品类型', name: 'category.name', index: 'category_id', align:"center", width: 100},
            /*{label: '商品序列号', name: 'goodsSn', index: 'goods_sn', width: 1300},*/
            {label: '名称', name: 'name', index: 'name', align:"center", width: 150},
            /*{label: '品牌', name: 'brandName', index: 'brand_id', width: 120},*/
            /*{label: '关键字', name: 'keywords', index: 'keywords', width: 1300},*/
            /*{label: '简明介绍', name: 'goodsBrief', index: 'goods_brief', width: 1300},*/
            {label: '价钱(元)', name: 'unitPrice', index: 'unit_price', align:"center", width: 80},
            {
                label: '上架', name: 'isOnSale', index: 'is_on_sale', width: 50,
                formatter: function (value) {
                    return transIsNot(value);
                }
            },
            {
                label: '录入日期', name: 'createTime', index: 'create_time', align:"center", width: 150, formatter: function (value) {
                    console.log(value);
                return transDate(value, 'yyyy-MM-dd');
            }
            },
            {label: '出版社', name: 'publisher', index: 'publisher', align:"center", width: 150},
            {label: 'ISBN号', name: 'isbn', index: 'isbn', align:"center", width: 150},

            {label: '销售量', name: 'saleNum', index: 'sale_num',align:"center", width: 80},
            {label: '借阅量', name: 'broNum', index: 'bro_num',align:"center", width: 80},
            {label: '商品库存', name: 'storage', index: 'storage',align:"center", width: 80},
            {label: '评分', name: 'grade', index: 'grade',align:"center", width: 80},

            {label: '新品', name: 'isNew', index: 'is_new',align:"center", width: 50,
                formatter: function (value) {
                    return transIsNot(value);
                }},
            {
                label: '热销', name: 'isHot', index: 'is_hot', align:"center",width: 50,
                formatter: function (value) {
                    return transIsNot(value);
                }
            },
            {label: '商品主图', name: 'listPicUrl', index: 'list_pic_url',align:"center", width: 200 },
            {label: '商品描述', name: 'detail', index: 'detail', align:"center", width: 200}
        ],
        viewrecords: true,
        height: 385,
        rowNum: 10,
        rowList: [10, 30, 50],
        rownumbers: true,
        rownumWidth: 25,
        autowidth: true,
        multiselect: true,
       /* autoScroll: false,*/
        shrinkToFit:true,
        pager: "#jqGridPager",
        jsonReader: {
            root: "page.list",
            page: "page.pageNum",
            total: "page.pages",
            records: "page.total"
        },
        prmNames: {
            page: "page",
            rows: "limit",
            order: "order"
        },
    gridComplete: function () {
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({"overflow-x" : "scroll"});
            /*$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-y" : "scroll" });*/
    }
    });

    $('#bookDesc').editable({
        inlineMode: false,
        alwaysBlank: true,
        height: '500px', //高度
        minHeight: '200px',
        language: "zh_cn",
        spellcheck: false,
        plainPaste: true,
        enableScript: false,
        imageButtons: ["floatImageLeft", "floatImageNone", "floatImageRight", "linkImage", "replaceImage", "removeImage"],
        allowedImageTypes: ["jpeg", "jpg", "png", "gif"],
        imageUploadURL: '../file/upload',
        imageUploadParams: {id: "edit"},
        //imagesLoadURL: '../sys/oss/queryAll'
    })

    //表格宽度自适应
    $(function(){
        $(window).resize(function(){
            $("#jqGrid").setGridWidth($(window).width());
        });
    });

    $(function () {
        $.ajax({
            type: "POST",
            url: "../category/queryAll",
            success:function (r) {
                vm.categoryList = r.list
            }
        });
        //vm.getCategory();
    });

});

var ztree;

var setting = {   //树形结构设置
    data: {
        simpleData: {
            enable: true,
            idKey: "code",
            pIdKey: "parentCode",
            rootPId: "-1"
        },
        key: {
            url: "nourl"
        }
    }
};
var vm = new Vue({
    el: '#rrapp',
    data: {
        showList: true,
        title: null,
        uploadList: [],
        categoryList:[],
        imgName: '',
        visible: false,
        books: {
            pic:'',
            categoryId: '',
            isOnSale: 1,
            isNew: 1,
            isHot: 1,
            isLimited: 1,
            category: '',
            categoryName:null
        },
        ruleValidate: {
            name: [
                {required: true, message: '名称不能为空', trigger: 'blur'}
            ]
        },
        q: {
            name: '',
            categoryId:''
        },

    },
    methods: {
        query: function () { //搜索
            vm.reload();
        },
        add: function () {
            vm.showList = false;
            vm.title = "新增";
            vm.uploadList = [];
            vm.books = {
                pic:'',
                categoryId: '',
                isOnSale: 1,
                isNew: 1,
                isLimited: 1,
                isHot: 1,
                category: '',
                categoryName:null
            };
            vm.getCategory();
            $('#bookDesc').editable('setHTML', '');
        },
        update: function (event) {
            var id = getSelectedRow();
            if (id == null) {
                return;
            }
            //vm.getInfo(id);
            $.get("../book/info/" + id, function (r) {
                vm.showList = false;
                vm.title = "修改";
                vm.books = r.book;
                console.log(r.book.category)
                vm.getCategory();
            });
        },

        saveOrUpdate: function (event) {
           var url = "../book/saveOrUpdate";
            vm.books.detail = $('#bookDesc').editable('getHTML');
            $.ajax({
                type: "POST",
                url: url,
                contentType: "application/json",
                data: JSON.stringify(vm.books),
                success: function (r) {
                    if (r.status === "0000") {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        enSale: function () {
            var id = getSelectedRow();
            if (id == null) {
                return;
            }
            confirm('确定要上架选中的商品？', function () {
                $.ajax({
                    type: "POST",
                    url: "../book/enSale",
                    contentType: "application/json",
                    data: JSON.stringify(id),
                    success: function (r) {
                        if (r.status == "00000") {
                            alert('操作成功', function (index) {
                                $("#jqGrid").trigger("reloadGrid");
                            });
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        unSale: function () {
            var id = getSelectedRow();
            if (id == null) {
                return;
            }
            confirm('确定要下架选中的商品？', function () {
                $.ajax({
                    type: "POST",
                    url: "../book/unSale",
                    contentType: "application/json",
                    data: JSON.stringify(id),
                    success: function (r) {
                        if (r.status == "00000") {
                            alert('操作成功', function (index) {
                                $("#jqGrid").trigger("reloadGrid");
                            });
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        del: function (event) {
            var ids = getSelectedRows();
            if (ids == null) {
                return;
            }
            confirm('确定要删除选中的记录？', function () {
                $.ajax({
                    type: "POST",
                    url: "../book/delete",
                    contentType: "application/json",
                    data: JSON.stringify(ids),
                    success: function (r) {
                        if (r.status == "00000") {
                            alert('操作成功', function (index) {
                                $("#jqGrid").trigger("reloadGrid");
                            });
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        getInfo: function (id) {
            $.get("../book/info/" + id, function (r) {
                vm.books = r.book;
                vm.getCategory();
                $('#bookDesc').editable('setHTML', vm.books.detail);
            });
        },
        reload: function (event) {  //查找也能用到
            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: {'name': vm.q.name,'categoryId':vm.q.categoryId},
                page: page
            }).trigger("reloadGrid");
            vm.handleReset('formValidate');
        },
        getCategory: function () {
            //加载分类树
            $.get("../category/getCategorySelect", function (r) {
                ztree = $.fn.zTree.init($("#categoryTree"), setting, r.list);
                var node = ztree.getNodeByParam("code", vm.books.category.code);
                if (node) {
                    ztree.selectNode(node);
                    vm.books.category = node;
                } else {
                    node = ztree.getNodeByParam("code", 0);
                    ztree.selectNode(node);
                    vm.books.category = node;
                }
            })
        },
        categoryTree: function () {
            layer.open({
                type: 1,
                offset: '50px',
                skin: 'layui-layer-molv',
                title: "选择类型",
                area: ['300px', '450px'],
                content: jQuery("#categoryLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var node = ztree.getSelectedNodes();
                    //选择上级菜单
                    vm.books.categoryId = node[0].id;
                    //vm.books.categoryName = node[0].name;
                    vm.books.category = node[0];

                    //搜索分类


                    layer.close(index);
                }
            });
        },
        categorySelect: function () {

        },
        handleView(name) {
            this.imgName = name;
            this.visible = true;
        },
        handleRemove(file) {
            // 从 upload 实例删除数据
            const fileList = this.uploadList;
            this.uploadList.splice(fileList.indexOf(file), 1);
        },
        handleSuccess(res, file) {
            // 因为上传过程为实例，这里模拟添加 url
            file.imgUrl = res.url;
            file.name = res.url;
            vm.uploadList.add(file);
        },
        handleBeforeUpload() {
            const check = this.uploadList.length < 5;
            if (!check) {
                this.$Notice.warning({
                    title: '最多只能上传 5 张图片。'
                });
            }
            return check;
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleFormatError: function (file) {
            this.$Notice.warning({
                title: '文件格式不正确',
                desc: '文件 ' + file.name + ' 格式不正确，请上传 jpg 或 png 格式的图片。'
            });
        },
        handleMaxSize: function (file) {
            this.$Notice.warning({
                title: '超出文件大小限制',
                desc: '文件 ' + file.name + ' 太大，不能超过 2M。'
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        },
        handleSuccessListPicUrl: function (res, file) {
            vm.books.listPicUrl = file.response.url;
        },
        eyeImageListPicUrl: function () {
            var url = vm.books.listPicUrl;
            eyeImage(url);
        },
        eyeImage: function (e) {
            eyeImage($(e.target).attr('src'));
        }
    }/*,
    mounted() {
        this.uploadList = this.$refs.upload.fileList;
    }*/
});